package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pojo.User;
import service.UserManager;
import service.impl.UserManagerFactory;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	private UserManager manager;
	
    public LoginServlet() {
        super();
        manager = UserManagerFactory.getInstance();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("uname");
		String psd = request.getParameter("psd");
		
		//TODO: 要用Logger
		Logger logger = Logger.getLogger(LoginServlet.class);
		logger.info("有人发起登录： 用户名："+uname);
		
		///判断一波
		manager = UserManagerFactory.getInstance();
		User user = manager.checkLoginUser(uname, psd);
		if(user!=null){
			logger.info( "用户名："+uname+"登录成功");
			request.getSession().setAttribute("user", user);
			request.getRequestDispatcher("sec/AddServlet").forward(request, response);
		}else{
			logger.info("登录失败");
			request.setAttribute("error_uname", "登录失败");
			request.setAttribute("error_psd", "登录失败");
			request.setAttribute("uname", uname);
			request.setAttribute("psd", psd);
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
